import pandas as pd

#创建记账记录表
df = pd.read_csv('records.csv')
#print(df)
df.set_index('ID', inplace=True)
df['金额'] = df['金额'].astype(float)
df['时间'] = pd.to_datetime(df['时间'])

#登录
def login_system():
#账户（用户名：[密码,角色]）
    users={
        "admin":["123456","admin"],
        "lisi":["123456","user"]
    }

    temp=0
    while temp<3:
        username=input("用户名：").strip()
        password=input("密码").strip()

        #验证
        if username in users and password == users[username][0]:
            print(f"\n登陆成功！{'管理员'if users[username][1]=='admin' else '普通用户'}界面加载中")
            manu_interface(users[username][1])
            return
        else:
            temp+=1
            remaining=3 - temp
            print(f"\n验证失败，剩余尝试次数：{remaining}\n")

    print("三次验证失败，系统已锁定")
    exit()

#菜单
def manu_interface(role):
    manu={
        "admin":["1.添加账务","2.编辑账务","3.删除账务","4.查询账务","5.退出系统"],
        "user":["1.查询所有","2.按条件查询"]
    }
    print("\n=======家庭记账系统=======\n")

    if role == "admin":
        while True:
            print(" ".join(manu[role]))
            action=input("请输入要操作的功能序号[1-5]:")
            if action == "1":
                add_record(df)
            elif action == "2":
                id=int(input("请输入要编辑账务的ID:"))
                edit_record(id,df)
            elif action == "3":
                id=int(input("请输入要删除账务的ID:"))
                delete_record(id,df)
            elif action == "4":
                select_record(df)
            elif action == "5":
                exit()
            else:
                print("非法操作，请重新输入！")
    else:
        select_record(df)
#添加
def add_record(df):
    try:
        # 带校验的输入
        record = {
            '类别': input("类别：").strip(),
            '账户': input("账户：").strip(),
            '金额': float(input("金额：").strip()),
            '时间': pd.to_datetime(input("时间（YYYY-MM-DD）：").strip()),
            '说明': input("说明：").strip()
        }
    except ValueError as e:
        print(f"输入错误：{str(e)}")

    next_idx = max(df.index) + 1
    df.loc[next_idx] = record
    print(f"添加成功！\n新记录：{record}\n")
    return df

#删除
def delete_record(id,df):
    if id in df.index:
        df.drop(id,inplace=True)
        print("账务删除成功")
    else:
        print("未找到ID！\n")

#编辑
def edit_record(id,df):
    if id not in df.index:
        print("未找到ID！\n")
        return df

    print(f"\n已找到id为{id}的账务：{df.loc[id]}\n")

    ch=['类别','账户','金额','时间','说明']
    try:
        a = int(input("请选择要编辑的列（1.类别 2.账户 3.金额 4.时间 5.说明）：").strip()) - 1
    except ValueError:
        print("输入必须为数字！")
        return df

    if 0 <= a < len(ch):
        new_value = input("请输入修改后的值：")
        # 数据类型处理
        if ch[a] == '金额':
            try:
                new_value = float(new_value)
            except ValueError:
                print("金额必须为数字！")
                return df
        elif ch[a] == '时间':
            try:
                new_value = pd.to_datetime(new_value)
            except ValueError:
                print("时间格式错误（示例：2025-01-01）")
                return df
        df.at[id, ch[a]] = new_value
        print("修改成功")
    else:
        print("无效的列编号！\n")

    return df

#查询
def select_record(df):
    while True:
        action=input("请选择功能[1-3]：1.查询所有 2.按条件查询 3.退出查询:")
        if action == "1":
            print(df)
        elif action == "2":
            try:
                values = int(input("请选择查询条件[1-3]：1.类别 2.账户 3.时间：").strip())
            except ValueError:
                print("错误：请输入数字编号！")
                continue

            if values == 1:
                select1=str(input("请输入类别：").strip())
                filtered = df[df['类别'].isin([select1])]
                print(f"\n记账记录中类别为【{select1}】的记录共{len(filtered)}条：\n")

            elif values == 2:
                select1 = str(input("请输入账户：").strip())
                filtered = df[df['账户'].isin([select1])]
                print(f"\n记账记录中账户为【{select1}】的记录共{len(filtered)}条：\n")

            elif values == 3:
                try:
                    select1 = pd.to_datetime(input("请输入时间（YYYY-MM-DD）：").strip())
                    filtered = df[df['时间']==select1]
                except ValueError:
                    print("错误：时间格式应为YYYY-MM-DD（如2025-01-01）")
                    continue

                print(f"\n记账记录中时间为【{select1.date()}】的记录共{len(filtered)}条：\n")

            else:
                print("错误：请输入1-3的编号！")
                continue

            print(filtered.to_string(index=True) if not filtered.empty else "无相关记录")

        elif action == "3":
            return
        else:
            print("错误：请输入1-3的编号！")


if __name__ == "__main__":
    login_system()
